package com.zhou.es.service;

import com.alibaba.fastjson.JSON;
import com.zhou.es.pojo.Content;
import com.zhou.es.util.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zhouyongjun
 * @Description:
 * @date 2021/3/18 8:22
 */
@Service
public class ContentServiceImpl implements IContentService {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    static String INDEX = "jd_goods";

    @Override
    public boolean parseContent(String keywords) throws IOException {
        List<Content> contentList = HtmlParseUtil.parseJD(keywords);
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i < contentList.size(); i++) {
            bulkRequest.add(new IndexRequest(INDEX)

            .source(JSON.toJSONString(contentList.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulkResponses = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulkResponses.hasFailures();
    }

    @Override
    public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {
        SearchRequest searchRequest = new SearchRequest(INDEX);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //精准匹配
        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("title",keyword);
        sourceBuilder.query(termsQueryBuilder);
        //超时设置
        sourceBuilder.timeout(TimeValue.timeValueSeconds(60));
        //分页配置
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);
        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse  response = client.search(searchRequest,RequestOptions.DEFAULT);
        //解析结果
        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }
}
